# -*- coding: utf-8 -*-

"""https://developer.amazon.com/public/solutions/alexa/alexa-voice-service/reference/speechrecognizer"""

import logging
import sys
import threading
import time
import uuid
from . import Audio
if sys.version_info < (3, 0):
    import Queue as queue
else:
    import queue

from respeaker_source import RespeakerdSource
logger = logging.getLogger('SpeechRecognizer')


class SpeechRecognizer(object):


    def __init__(self):

        # self._audio=Audio()
        self._audio=RespeakerdSource()
        self._audio.link(self)
        self.audio_queue = queue.Queue(maxsize=1000)
        self.listening = False
        # self.conversation = 0
        self._audio.start()


    def put(self, audio):
        if self.listening:
            self.audio_queue.put(audio)

    def Recognize(self, timeout=10000):

        if self.listening:
            logger.debug('Already listening. Ignore')
            return

        logger.debug('Starting listening')

        self.audio_queue.queue.clear()
        self.listening = True

        def gen():
            time_elapsed = 0
            while self.listening and time_elapsed <= timeout:
                try:
                    chunk = self.audio_queue.get(timeout=1.0)
                except queue.Empty:
                    break

                yield chunk
                time_elapsed += len(chunk) * 1000 / (2 * 16000)  # 16000 fs, 2 bytes width
                logger.debug('Sending chunk, time_elapsed = {}'.format(time_elapsed))

            self.listening = False

        return gen()


    def StopCapture(self):
        self.listening = False
        logger.info('StopCapture')

    def onReady(self):
        self._audio.on_cloud_ready()



    def onThink(self):
        self.StopCapture()


    def onOff(self):
        pass

    def onListing(self):
        # self._audio.on_speak()
        pass

    def onSpeaking(self):
        self._audio.on_speak()
        pass



